<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

class m_website_actions_block_BlocksRightAction extends m_backoffice_extends_Action
{
	public function execute()
	{
		$documentId = $this->getRequestParameter("docId");
		$documentLang = $this->getRequestParameter("docLang");
		$blockId = $this->getRequestParameter("blockId");

        if($blockId == '0') $blockId = null;

		if(!is_null($documentId))
		{
            if(!empty($blockId) && !is_null($blockId))
            {
                $tempDocService = m_backoffice_services_TempDocService::getInstance();
                
                if($tempDocService->hasTemporary($documentId, $documentLang))
                {
                    $document = $tempDocService->getTemporaryDocument($documentId, $documentLang);
                }
                else
                {
                    $document = f_document_Provider::getInstance()->getByModelAndUniqueId('website/Page', $documentId, $documentLang);
                }
            }
            else
            {
                $document = f_document_Provider::getInstance()->getByModelAndUniqueId('website/Page', $documentId, $documentLang);
            }

            if($this->isSubmit())
            {
                if($this->saveRights($documentId, $documentLang, $blockId))
                {
                    $this->addToModel('formSuccess', 'true');
                }
            }

			if(!empty($blockId))
			{
				$block = $document->getBlockById($blockId);
			}
			else
			{
				$block["blockLabel"] = $document->getLabel();
				$block["blockId"] = "0";
				$block["front"] = $document->getRight();
			}
            
            $block["documentId"] = $documentId;
            $block["documentLang"] = $documentLang;

            $assignedUsers = null;
			if(isset($block["front"]) && !empty($block["front"]) && $block['front'] != '')
			{
                $assignedUsers = $this->getAssignedUsers($block['front']);
                
                $unAssignedGrps = $this->getUnAssignedGroups($assignedUsers);
			}
            else
            {
                $unAssignedGrps = $this->getUnAssignedGroups();
            }
		}

        $this->addToModel('assignedUsers', $assignedUsers);
        $this->addToModel('unAssignedGrps', $unAssignedGrps);

		$this->addToModel("block", $block);
		$this->setView('success');
	}

    private function getUnAssignedGroups($assignedUsers = null)
    {
        $unAssignedGrps = $this->getDocumentProvider()->loadDocuments('modules_users/Group')->retrieveDocuments();

        if(!is_null($assignedUsers))
        {
            foreach($unAssignedGrps as $k => $unAssignedGrp)
            {
                if(key_exists($unAssignedGrp->getUniqueId(), $assignedUsers))
                {
                    unset($unAssignedGrps[$k]);
                }
            }
        }

        return $unAssignedGrps;
    }

    private function getAssignedUsers($users)
    {
        $users = split(" ", $users);

        $assignedUsers = array();

        if(is_array($users) && count($users) > 0)
        {
            foreach($users as $userId)
            {
                $assignedUsers[$userId] = $this->getDocumentProvider()->getByUniqueId($userId);
            }
        }

        return $assignedUsers;
    }

    private function isSubmit()
    {
        $formValues = $this->getFormValues('form');
        if(!is_null($formValues) && is_array($formValues) && isset($formValues['submit']))
        {
            return true;
        }
        return false;
    }

    private function saveRights($docId, $docLang, $blockId)
    {
        if(!is_null($blockId))
        {
            return $this->saveBlockRights($docId, $docLang, $blockId);
        }
        else
        {
            return $this->savePageRights($docId, $docLang);
        }
    }

    private function saveBlockRights($docId, $docLang, $blockId)
    {
        $formValues = $this->getFormValues('form');

        $tempDocService = m_backoffice_services_TempDocService::getInstance();

		if($tempDocService->hasTemporary($docId, $docLang))
		{
			$page = $tempDocService->getTemporaryDocument($docId, $docLang);
		}
		else
		{
			$page = f_document_Provider::getInstance()->getByModelAndUniqueId('website/Page', $docId, $docLang);
		}

        $block = $page->getBlockById($blockId);

        $items = is_null($formValues['userItem']) ? null : join(' ', $formValues['userItem']);

        if(is_null($items) && isset($block['front']))
        {
            unset($block['front']);
        }
        else
        {
            $block['front'] = $items;
        }

        $page->setBlockParamsById($blockId, $block);
        $tempDocService->saveTemporaryDocument($page);

        return true;
    }

    private function savePageRights($docId, $docLang)
    {
        $formValues = $this->getFormValues('form');
        $page = f_document_Provider::getInstance()->getByModelAndUniqueId('website/Page', $docId, $docLang);

        $items = is_null($formValues['userItem']) ? '' : join(' ', $formValues['userItem']);

        return $page->setRight($items);
    }
	
	public function validate()
	{
		return $this->getUserContext()->hasRight(array("website_TabPageProperties", "website_BlockEdit"), "OR");
	}
}